﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace CMWVS.Core.Mono
{
    public class MonoCompiler: RelayCommand<MonoCompilerParams, MonoCompilerResult>
    {
     
#region Constructor

        private MonoCompiler()
        {

        }

        public MonoCompiler(MonoConfig config)
        {
            m_MonoConfig = config;
            this.SetCommands();
        }


#endregion

        private MonoConfig m_MonoConfig;

        private void SetCommands()
        {
           
            base.m_CanExecute = () =>
                {
                    return m_MonoConfig.IsInstalled;
                };
            base.m_Commmand = (compileParameter) =>
                {
                    if ((m_MonoConfig.MonoCompiler.Exists) && (null != compileParameter.SLN) && (compileParameter.SLN.SolutionFile.Exists))
                    {

                        StringBuilder compilerArguments = new StringBuilder(compileParameter.SLN.SolutionFile.Name);
                        compilerArguments.Append(" ");
                        compilerArguments.Append(compileParameter.Target.Target);

                        ProcessStartInfo psi = new ProcessStartInfo(m_MonoConfig.MonoCompiler.FullName, compilerArguments.ToString());
                        psi.UseShellExecute = false;
                        psi.WorkingDirectory = compileParameter.SLN.SolutionFile.Directory.FullName;
                        psi.CreateNoWindow = true;
                        psi.RedirectStandardOutput = true;

                        Process p = new Process();
                        p.StartInfo = psi;
                        p.Start();
                        while (!p.StandardOutput.EndOfStream)
                        {
                            compileParameter.Listener.WriteLine(p.StandardOutput.ReadLine());
                        }
                        //p.WaitForExit();
                    }

                    return new MonoCompilerResult();
                };
        
        }
        
    }
}
